<template>
  <Form ref="formDom" :validation-schema="mySchema" #default="{ errors }" autocomplete="off" class="xtx-form">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{ nickName }}欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{ err: errors.mobile }" v-model="form.mobile" name="mobile" class="input" type="text"
          placeholder="绑定的手机号" />
      </div>
      <div v-if="errors.mobile" class="error"><i class="iconfont icon-warning" />{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{ err: errors.code }" v-model="form.code" name="code" class="input" type="text"
          placeholder="短信验证码" />
        <span class="code" @click="send">{{ countDown === 0 ? '发送验证码' : `${countDown}后重新发送` }}</span>
      </div>
      <div v-if="errors.code" class="error"><i class="iconfont icon-warning" />{{ errors.code }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即绑定</a>
  </Form>
</template>

<script lang="ts" setup>
import { reactive, ref, onUnmounted } from 'vue'
import veeSchema from '../../utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import { useIntervalFn } from '@vueuse/core'
import message from '../../components/library/message'
import userStore from '../../store/index.js'
import { useRouter, useRoute } from 'vue-router'
import { userQQBindCode, userQQBindLogin } from '../../api/user'
// 1. 准备下信息：unionId(openId) qq头像 昵称
const prpos = defineProps({
  unionId: {
    type: String,
    default: ''
  }
})
// QQ用户名字
const nickName = ref(null)
// QQ用户头像
const avatar = ref(null)
if (window.QC.Login.check()) {
  window.QC.api('get_user_info').success(res => {
    avatar.value = res.data.figureurl_qq_1
    nickName.value = res.data.nickname
  })
}
// 2. 完成表单校验
// 表单数据对象
const form = reactive({
  mobile: null,
  code: null
})
// 校验规则对象
const mySchema = {
  mobile: veeSchema.mobile,
  code: veeSchema.code
}
// 3. 发送验证吗（校验，定义api，调用，完成倒计时）
// pause 暂停 resume 开始
// useIntervalFn(回调函数,执行间隔,是否初始化立即开启)
// 设计一个倒计时
const countDown = ref(0)
// 取得表达的Dom来清空规则
const formDom: any = ref(null)
const { pause, resume } = useIntervalFn(() => {
  countDown.value--
  if (countDown.value <= 0) {
    pause()
  }
}, 1000, { immediate: false })
// 销毁组件时销毁倒计时
onUnmounted(() => {
  pause()
})
// 1.1发送验证码绑定发送事件
const send = async () => {
  const valid = mySchema.mobile(form.mobile)
  // 验证通过
  if (valid === true) {
    // 倒计时事件已经过了,才可重新发送验证码
    if (countDown.value === 0) {
      await userQQBindCode(form.mobile).catch(rej => {
        if (rej.response.status === 400) {
          message({ type: 'error', text: '用户不存在', countDown: 1500 })
        } else {
          message({ type: 'success', text: '发送成功', countDown: 1500 })
          countDown.value = 60
          resume()
        }
      }
      )
    }
  } else {
    // 验证不通过
    // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
    formDom.value.setFieldError('mobile', valid)
  }
}
// 4. 进行绑定（绑定成功就是登录成功）
const { user } = userStore()
const router = useRouter()
const route: any = useRoute()
const submit = async () => {
  // 对信息进行全部认证,并返回一个Promise
  const valid = formDom.value.validate()
  if (valid) {
    // 发起绑定手机号请求
    userQQBindLogin({ unionId: prpos.unionId, ...form }).then((res: any) => {
      const { id, account, avatar, mobile, nickname, token } = res.result
      // 存储用户信息
      user.setUser({ id, account, avatar, mobile, nickname, token })
      // 3. 跳转要原来页或首页
      router.push(route.query.redirectUrl || '/')
      message({ type: 'success', text: 'QQ绑定成功', countDown: 1500 })
    }).catch(e => { message({ type: 'error', text: 'QQ绑定成功失败', countDown: 1500 }) })
  }
}
</script>

<style  lang='less' scoped>
@import '../../assets/styles/mixins.less';
@import '../../assets/styles/variables.less';

.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;

  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }

  p {
    padding-left: 10px;
  }

  >.error {
    position: absolute;
    font-size: 12px;
    line-height: 28px;
    color: @priceColor;

    i {
      font-size: 14px;
      margin-right: 2px;
    }
  }
}

.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;

  &:hover {
    cursor: pointer;
  }
}
</style>